<?php

namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Controller;
use App\Models\TeacherModel;
use App\Models\StudentModel;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function login(Request $request) {
        // 先通过openid查询用户是老师还是学生
        $openid = $request->input('openid');
        $teacher = TeacherModel::where('wx_id', $openid)->first();
        if ($teacher) {
            $teacher->role = 'teacher';
            return self::ok($teacher, '登录成功');
        }
        $student = StudentModel::where('parent_wx_id', $openid)->first();
        if ($student) {
            $student->role = 'student';
            return self::ok($student, '登录成功');
        }
        return self::err('请先绑定用户信息', 201);
    }

    public function bindWX(Request $request) {
        // 绑定openid
        $role = $request->input('role'); // 角色，teacher或student
        $name = trim($request->input('name')); // 姓名
        $phone = trim($request->input('phone')); // 手机号
        $openid = $request->input('openid');

        if ($role === 'teacher') {
            // 教师绑定逻辑
            // 检查手机号是否已被绑定
            $teacher = TeacherModel::where('name', $name)->where('phone', $phone)->first();

            if (!$teacher) {
                return self::err('未匹配到老师信息');
            }

            if ($teacher->wx_id) {
                return self::err('该教师已绑定过微信');
            }
            $teacher->wx_id = $openid;
            $teacher->save();
        } else {
            // 学生绑定逻辑
            // 检查手机号是否已被绑定
            $student = StudentModel::where('name', $name)->where('parent_phone', $phone)->first();
            if (!$student) {
                return self::err('未找到信息匹配的学员，请联系老师');
            }
            if ($student->parent_wx_id) {
                return self::err('该学生已绑定过微信');
            }
            $student->parent_wx_id = $openid;
            $student->save();
        }
        return self::ok([], '绑定成功');
    }
}
